//
//  NSDictionary+FYJSafeAccessor.m
//  AFNetworking
//
//  Created by jrwh_mac01 on 2021/8/25.
//

#import "NSDictionary+FYJSafeAccessor.h"

@implementation NSDictionary (FYJSafeAccessor)

- (NSString *)fyj_stringForKey:(id)key
{
    return [self fyj_stringForKey:key or:nil];
}

- (NSString *)fyj_stringForKey:(id)key or:(NSString *)fall
{
    NSObject *result = [self fyj_objectForKey:key expectedClass:[NSString class] or:fall];
    if (result) {
        return (NSString *)result;
    }
    result = [self fyj_objectForKey:key expectedClass:[NSNumber class] or:fall];
    if (result) {
        return [NSString stringWithFormat:@"%@", result];
    }
    return nil;
}

- (NSNumber *)fyj_numberForKey:(id)key
{
    return [self fyj_numberForKey:key or:nil];
}

- (NSNumber *)fyj_numberForKey:(id)key or:(NSNumber *)fall
{
    NSObject *result = [self fyj_objectForKey:key expectedClass:[NSNumber class] or:fall];
    if (result) {
        return (NSNumber *)result;
    }
    result = [self fyj_objectForKey:key expectedClass:[NSString class] or:fall];
    if (result) {
        return @([(NSString *)result doubleValue]);
    }
    return nil;
}

- (NSInteger)fyj_integerForKey:(id)key
{
    return [[self fyj_numberForKey:key] integerValue];
}

- (float)fyj_floatForKey:(id)key
{
    return [[self fyj_numberForKey:key] floatValue];
}

- (double)fyj_doubleForKey:(id)key
{
    return [[self fyj_numberForKey:key] doubleValue];
}

- (long long)fyj_longlongForKey:(id)key
{
    return [[self fyj_numberForKey:key] longLongValue];
}

- (BOOL)fyj_boolForKey:(id)key
{
    NSString *value = [self fyj_stringForKey:key];
    if ([value isEqualToString:@"true"]) {
        return YES;
    }
    return [[self fyj_numberForKey:key] boolValue];
}

- (NSDictionary *)fyj_dictionaryForKey:(id)key
{
    return [self fyj_dictionaryForKey:key or:nil];
}

- (NSDictionary *)fyj_dictionaryForKey:(id)key or:(NSDictionary *)fall
{
    return [self fyj_objectForKey:key expectedClass:[NSDictionary class] or:fall];
}

- (NSArray *)fyj_arrayForKey:(id)key
{
    return [self fyj_arrayForKey:key or:nil];
}

- (NSArray *)fyj_arrayForKey:(id)key or:(NSArray *)fall
{
    return [self fyj_objectForKey:key expectedClass:[NSArray class] or:fall];
}

- (NSData *)fyj_dataForKey:(id)key
{
    return [self fyj_dataForKey:key or:nil];
}

- (NSData *)fyj_dataForKey:(id)key or:(NSData *)fall
{
    return [self fyj_objectForKey:key expectedClass:[NSData class] or:fall];
}

- (id)fyj_objectForKey:(id)key
{
    id obj = [self fyj_objectForKey:key expectedClass:[NSObject class]];
    if ([obj isEqual:[NSNull null]]) {
        return nil;
    }
    return obj;
}

- (id)fyj_objectForKey:(id)key expectedClass:(Class)class
{
    return [self fyj_objectForKey:key expectedClass:class or:nil];
}

- (id)fyj_objectForKey:(id)key expectedClass:(Class)class or:(id)fall
{
    id obj = [self objectForKey:key];
    if (class && [obj isKindOfClass:class]) {
        return obj;
    }
    return fall;
}

@end
